#!/bin/sh

set -e

if test "$1" = "--version"; then
	echo `perl -MDebian::PkgJs::Version -e 'print $VERSION'`
	exit
fi
if test "$1" = "--help" || test "$1" = "-h"; then
	cat <<EOT
Usage: github-debian-upstream

Simply launch github-debian-upstream in a source Debian directory. If
debian/control or debian/copyright contains a valid GitHub link, this
tool will generate debian/upstream/metadata file. It adds automatically
the file using "git add" and displays result. You can then modify it.
Don't forget to launch a "git commit".

Copyright (C) Yadd <yadd@debian.org>

Licensed under GPL-2+ (see /usr/share/common-licenses/GPL-2)
EOT
	exit
fi

if test "$1" = "--version"; then
	perl -MDebian::PkgJs::Version -le 'print $VERSION'
    exit
fi

if test -e debian/upstream/metadata; then
	echo "debian/upstream/metadata found" >&2
	exit 1
fi

upstream=`perl -ne 'if(s@.*github.com/([^/]+)/([^/#]+).*$@$1/$2@){print;exit}' debian/copyright`

if test "$upstream" = ""; then
	echo "Trying control" >&2
	upstream=`perl -ne 'if(s@.*github.com/([^/]+)/([^/#]+).*$@$1/$2@){print;exit}' debian/control`
fi
if test "$upstream" = ""; then
	echo Not found >&2
	exit 1
fi

name=${upstream#*/}

mkdir -p debian/upstream
cat >debian/upstream/metadata <<EOF
---
Archive: GitHub
Bug-Database: https://github.com/$upstream/issues
Bug-Submit: https://github.com/$upstream/issues/new
Changelog: https://github.com/$upstream/tags
Repository: https://github.com/$upstream.git
Repository-Browse: https://github.com/$upstream
EOF

git add debian/upstream/metadata || true
cat debian/upstream/metadata
echo
echo "git commit debian/upstream/metadata -m 'Add upstream/metadata'"

